﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using HtmlAgilityPack;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using NLog;
using Quartz;

namespace CurrencySpider.BackGroundJob
{
    public class CnySpider : IJob
    {
        private readonly ILogger _logger = LogManager.GetCurrentClassLogger();
        /// <summary>
        /// 执行作业
        /// </summary>
        /// <param name="context"></param>
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                #region 爬取汇率信息
                // http://ratchadaexchange.com/?from=message&isappinstalled=0
                var url = string.Format($"{System.Configuration.ConfigurationManager.AppSettings["TarGetUrl"]}" +
                                        $"from={System.Configuration.ConfigurationManager.AppSettings["from"]}" +
                                        $"&isappinstalled={System.Configuration.ConfigurationManager.AppSettings["isappinstalled"]}");
                string html = GetHtml(url);
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);
                HtmlNode node = doc.DocumentNode;
                var list = new List<Rmb>();
                for (int i = 0; i < 4; i++)
                {
                    var divCny = node.SelectNodes("//tbody/tr[@id='CNY']")[i];
                    list.Add(new Rmb { Name = divCny.ChildNodes[1].InnerText, BuyCurrency = decimal.Parse(divCny.ChildNodes[3].InnerText), SellCurrency = decimal.Parse(divCny.ChildNodes[5].InnerText) });
                }
                #endregion

                _logger.Debug(JsonConvert.SerializeObject(list));

                #region 添加到数据库

                var createTime = DateTime.Now;
                foreach (var rmb in list)
                {
                    var sql = String.Format(
//                        "INSERT INTO ml_currency (Id,`Name`,BuyCurrency,SellCurrency,CreateTime) VALUES('{0}','{1}','{2}','{3}','{4}')"
                        "INSERT INTO ml_currency (`Name`,BuyCurrency,SellCurrency,CreateTime) VALUES('{0}','{1}','{2}','{3}')"
//                        , Guid.NewGuid(), rmb.Name, rmb.BuyCurrency, rmb.SellCurrency, createTime);
                        ,  rmb.Name, rmb.BuyCurrency, rmb.SellCurrency, createTime);
                    MySqlHelper.ExecuteScalar(MySqlHelper.Conn, CommandType.Text, sql);
                }
                #endregion
            }
            catch (Exception e)
            {
                _logger.Debug(e, $"人民币爬虫作业：定时人民币爬虫作业异常。异常信息：{e.Message}");
            }
        }
        static string GetHtml(string url)
        {

            WebRequest request = WebRequest.Create(url);
            WebResponse res = request.GetResponse();
            string html;
            using (StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8))
            {
                html = sr.ReadToEnd();
                sr.Close();
                res.Close();
            }
            return html;
        }
    }
}